﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;
using System.Web;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Web.Script.Serialization;
using Model;

namespace CommonCs
{
    public class Common
    {
        #region List和DataTable的互相转换
        /// <summary>
        /// DataTable to List
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<T> DataTableToList<T>(DataTable dt) where T : new()
        {
            if (dt == null)
            {
                return null;
            }
            System.Data.DataColumnCollection columns = dt.Columns;
            int iColumnCount = columns.Count;
            int i;
            int j;
            T entity = new T();
            Type elementType;
            elementType = entity.GetType();
            System.Reflection.PropertyInfo[] publicProperties = elementType.GetProperties();
            List<T> result = new List<T>();
            if (publicProperties.Length == iColumnCount)
            {
                foreach (DataRow currentRow in dt.Rows)
                {
                    for (i = 0; i < iColumnCount; i++)
                    {
                        for (j = 0; j < publicProperties.Length; j++)
                        {
                            if (columns[i].ColumnName == publicProperties[j].Name)
                            {
                                publicProperties[j].SetValue(entity, currentRow[i], null);
                            }
                        }
                    }
                    result.Add(entity);
                    entity = new T();
                }
            }
            else
            {
                result = null;
            }
            return result;
        }

        /// <summary>
        /// List to DataTable
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entitys"></param>
        /// <returns></returns>
        public static DataTable ListToDataTable<T>(List<T> entitys)
        {
            //检查实体集合不能为空
            if (entitys == null || entitys.Count < 1)
            {
                throw new Exception("需转换的集合为空");
            }
            //取出第一个实体的所有Propertie
            Type entityType = entitys[0].GetType();
            PropertyInfo[] entityProperties = entityType.GetProperties();
            //生成DataTable的structure
            //生产代码中，应将生成的DataTable结构Cache起来，此处略
            DataTable dt = new DataTable();
            for (int i = 0; i < entityProperties.Length; i++)
            {
                //dt.Columns.Add(entityProperties[i].Name, entityProperties[i].PropertyType);
                dt.Columns.Add(entityProperties[i].Name);
            }
            //将所有entity添加到DataTable中
            foreach (object entity in entitys)
            {
                //检查所有的的实体都为同一类型
                if (entity.GetType() != entityType)
                {
                    throw new Exception("要转换的集合元素类型不一致");
                }
                object[] entityValues = new object[entityProperties.Length];
                for (int i = 0; i < entityProperties.Length; i++)
                {
                    entityValues[i] = entityProperties[i].GetValue(entity, null);
                }
                dt.Rows.Add(entityValues);
            }
            return dt;
        }
        #endregion

        #region 写文件
        /****************************************
         * 函数名称：WriteFile
         * 功能说明：当文件不存时，则创建文件，并追加文件
         * 参    数：Path:文件路径,Strings:文本内容
         * 调用示列：
         *      string Path = Server.MapPath("Default2.aspx");       
         *      string Strings = "这是我写的内容啊";
         *      FileOperate.WriteFile(Path,Strings);
         *      Common.Common.WriteFile("~/aaa/test.aspx", "sss");
        *****************************************/
        /// <summary>
        /// 写文件
        /// </summary>
        /// <param name="Strings">文件的服务器路径</param>
        /// <param name="Strings">文件内容</param>

        public static void WriteFile(string name,string user, string Strings)
        {
            String path = HttpContext.Current.Server.MapPath("~\\SystemLog\\" + name + ".txt");
            if (!System.IO.File.Exists(path))
            {
                System.IO.FileStream f = System.IO.File.Create(path);
                f.Close();
                f.Dispose();
            }
            System.IO.StreamWriter f2 = new System.IO.StreamWriter(path, true, System.Text.Encoding.UTF8);
            Strings = "[" + DateTime.Now + "]" + Strings + "操作人[" + user + "]" + "\r\n" + "--------------------------------------------";
            f2.WriteLine(Strings);
            f2.Close();
            f2.Dispose();
        }

        public static void WriteFile(string name, string Strings)
        {
            String path = HttpContext.Current.Server.MapPath("~\\SystemLog\\" + name + ".txt");
            if (!System.IO.File.Exists(path))
            {
                System.IO.FileStream f = System.IO.File.Create(path);
                f.Close();
                f.Dispose();
            }
            System.IO.StreamWriter f2 = new System.IO.StreamWriter(path, true, System.Text.Encoding.UTF8);
            Strings = "[" + DateTime.Now + "]" + Strings + "\r\n" + "--------------------------------------------";
            f2.WriteLine(Strings);
            f2.Close();
            f2.Dispose();
        }

        public static void WriteFile(string Strings)
        {
            String path = "";
            
            path = HttpContext.Current.Server.MapPath("~\\OperFile\\OperFile.txt");
            
            if (!File.Exists(path))
            {
                FileStream f = File.Create(path);
                f.Close();
                f.Dispose();
            }
            StreamWriter f2 = new StreamWriter(path, true, System.Text.Encoding.UTF8);
            Strings = Strings + "\r\n" + "-----------------------------------------------------------------";
            f2.WriteLine(Strings);
            f2.Close();
            f2.Dispose();
        }
        #endregion

        #region  向前台传输单个json对象 和 数组json
        /// <summary>
        /// 将单个对象序列化成 json 字符串
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ObjectToJson(object obj)
        {
            if (obj == null)
            {
                return string.Empty;
            }
            JavaScriptSerializer myJson = new JavaScriptSerializer();

            return myJson.Serialize(obj);
        }

        /// <summary>
        /// 将datatable 转换成 [json,json]
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string DataTableToJson(DataTable dt)
        {
            if (dt == null || dt.Rows.Count == 0)
            {
                return "\"\"";
            }
            JavaScriptSerializer myJson = new JavaScriptSerializer();

            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();

            foreach (DataRow dr in dt.Rows)
            {
                Dictionary<string, object> result = new Dictionary<string, object>();
                foreach (DataColumn dc in dt.Columns)
                {
                    result.Add(dc.ColumnName, dr[dc].ToString());
                }
                list.Add(result);
            }
            return myJson.Serialize(list);
        }
        #endregion
    }
}
